<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>

</body>
<script>
// pid是parentId的简写,父id
let list = [
  {id: 1, name: '节点1', pid: ''},
  {id:11, name: '节点1-1', pid: 1},
  {id:111, name: '节点1-1-1', pid: 11},
  {id:12, name: '节点1-2', pid: 1},
  {id: 2, name: '节点2', pid: ''}
]

// list.forEach(t => {
//   let children = list.filter(m => m.pid === t.id)
//   if(children.length > 0) {
//     t.children = children
//   }
// })

// let result = list.filter(t => t.pid === '')
// console.log(result)

function translateListToTree(list,pid) {
   let arr = []
   list.forEach(t => {
    if(t.pid === pid) {
      let children = translateListToTree(list,t.id)
      if(children.length > 0) {
        t.children = children
      }
      arr.push(t)
    }
   })
   return arr
}
// 找第一级节点
let result = translateListToTree(list,'')
console.log(result)
</script>
</html>
